/**  
 * All rights Reserved, Designed By Android_Robot   
 * @Title:  DetectSystemActivity.java   
 * @Package com.jiyi.activity.new_maintenance   
 * @Description:    TODO(用一句话描述该文件做什么)   
 * @author: HYM     
 * @date:   2017-8-30 上午11:15:47   
 * @version V1.0     
 */  
package com.jiyi.activity.new_maintenance;

import android.app.Dialog;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.jiyi.bean.maintenance.DetectSystemJson;
import com.jiyi.bean.maintenance.DetectSystemJson.Equipment;
import com.jiyi.bean.maintenance.DetectSystemJson.SecEquipment;
import com.jiyi.common.StringInterface;
import com.jiyi.common.VolleyRequest;
import com.jiyi.easemob.util.UserHelp;
import com.jiyi.event.MaintenanceTaskListEvent;
import com.jiyi.event.UpdateMainDetectEvent;
import com.jiyi.inteface.WebApi;
import com.shizhefei.view.indicator.FragmentListPageAdapter;
import com.shizhefei.view.indicator.IndicatorViewPager;
import com.shizhefei.view.indicator.IndicatorViewPager.IndicatorFragmentPagerAdapter;
import com.shizhefei.view.indicator.ScrollIndicatorView;
import com.shizhefei.view.indicator.slidebar.ColorBar;
import com.shizhefei.view.indicator.transition.OnTransitionTextListener;
import com.swift.base.ActivityBase;
import com.swift.maintenance.R;
import com.swift.maintenance.base.AppBase;
import com.swift.maintenance.base.AppConfig;
import com.swift.maintenance.utils.ToastUtil;
import com.swift.maintenance.utils.UserInfoUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**   
 * @ClassName:  DetectSystemActivity   
 * @Description:TODO(检测系统，可输入状态)   
 * @author: HYM  
 * @date:   2017-8-30 上午11:15:47   
 *      
 */
public class DetectSystemActivity extends ActivityBase{

	/* 头部 */
	@BindView(R.id.tvBack)
	TextView tvBack;
	@BindView(R.id.tvTitle)
	TextView tvTitle;
	@BindView(R.id.tvSearch)
	TextView tvSearch;
	
	@BindView(R.id.moretab_indicator)
	ScrollIndicatorView indicator;
	@BindView(R.id.moretab_viewPager)
	ViewPager mViewPage;
	IndicatorViewPager indicatorViewPager;

	private LayoutInflater inflate;
	private String[] names;
	private boolean[] faults;
	
	private String title,id,company_id,code;
	Dialog dialog;
	
	List<SecEquipment> secEquipments = new ArrayList<SecEquipment>();
	int parentPosition,type,childPosition;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_detect_system);
		ButterKnife.bind(this);
		init();
	}
	
	/**   
	 * @author: HYM 
	 * @Title: init   
	 * @Description: TODO(这里用一句话描述这个方法的作用)    void 
	 * @date: 2017-9-9
	 */  
	private void init() {
		inflate = LayoutInflater.from(this);
		getIntentData();
		setTop();
		getData();
		EventBus.getDefault().register(this);
	}
	
	@Subscribe
	public void onUpdateMainDetectEvent(
			UpdateMainDetectEvent updateMainDetectEvent) {
		secEquipments.get(updateMainDetectEvent.position).setIs_finish(1);
		secEquipments.get(updateMainDetectEvent.position).setFaults(updateMainDetectEvent.faultNum);
		
		int status = 2;
		for (int i = 0; i < secEquipments.size(); i++) {
			SecEquipment secEquipment = secEquipments.get(i);
			if (secEquipment.getIs_finish() == 0) {
				status = 0;
				break;
			}
		}
		
		int faultNum= 0;
		for (int i = 0; i < secEquipments.size(); i++) {
			SecEquipment secEquipment = secEquipments.get(i);
			faultNum += secEquipment.getFaults();
		}
		
		Log.e("准备回传给列表页  ", "当前status"+status +"  当前faultNum "+faultNum);
		EventBus.getDefault().post(new MaintenanceTaskListEvent(type, parentPosition, childPosition, status,faultNum, 3));
	}
	
	@Override
	protected void onDestroy() {
		EventBus.getDefault().unregister(this);
		super.onDestroy();
	}

	private void getData() {
		Map<String, String> params = new HashMap<String, String>();
		params.put(AppConfig.ACCESS_TOKEN,
				UserInfoUtil.getCurrentUserAccessToken());
		params.put("id", id);
		params.put("code", code);

		dialog = showDialog(dialog);
		VolleyRequest.StringRequestPost(this, WebApi.MAINTENANCE_DETECT_SYSTEM,
				"", params, new StringInterface(this) {

					@Override
					public void stringSuccess(String result) {
						try {
							JSONObject obj = new JSONObject(result);
							String status = obj.getString("status");
							String info = obj.getString("info");
							if (status.equals("200")) {
								String data = obj.getString("data");
								DetectSystemJson dsj = new Gson().fromJson(data, DetectSystemJson.class);
								secEquipments = dsj.getSecEquipmentList();
								
								names = new String[secEquipments.size()];
								faults = new boolean[secEquipments.size()];
								for (int i = 0; i < secEquipments.size(); i++) {
									names[i] = secEquipments.get(i).getName();
									boolean isError = false; 
									for (int j = 0; j < secEquipments.get(i).getEquipment_list().size(); j++) {
										Equipment equip = secEquipments.get(i).getEquipment_list().get(j);
										if (!TextUtils.isEmpty(equip.getFault()) && equip.getFault().equals("1")) {
											isError = true;
											break;
										}
									}
									if (isError) {
										faults[i] = true;
									}
									else 
									{
										faults[i] = false;
									}
								}
								initIndication();
								
							} 
							else if (status.equals("404") && info.contains("尚未登录")) {
								ToastUtil.getInstances().showMsg("尚未登录或该用户在其他地方登录，请重新登录！");
								//清除环信登录
								UserHelp.getInstance().clearUser(AppBase.Context, true);
								return;
							}
							else {
								ToastUtil.getInstances().showMsg(info);
							}
						} catch (JSONException e) {
							e.printStackTrace();
						} finally {
							hideDialog(dialog);
						}
					}

					@Override
					public void stringError(VolleyError error) {
						hideDialog(dialog);
						ToastUtil.getInstances().showMsg(
								R.string.err_http_response);
					}
				});
	}

	/**   
	 * @author: HYM 
	 * @Title: getIntentData   
	 * @Description: TODO(这里用一句话描述这个方法的作用)    void 
	 * @date: 2017-8-30
	 */  
	private void getIntentData() {
		id = getIntent().getStringExtra("id") == null ? "" : getIntent().getStringExtra("id");
		title = getIntent().getStringExtra("title");
		code = getIntent().getStringExtra("code");
		if (!TextUtils.isEmpty(title) && title.length()>12) {
			title = title.substring(0, 12)+"...";
		}
		company_id = getIntent().getStringExtra(AppConfig.COMPANY_ID_KEY);
		parentPosition = getIntent().getIntExtra("parentPosition", 0);
		childPosition = getIntent().getIntExtra("childPosition", 0);
		type = getIntent().getIntExtra("type", 0);
	}

	private void setTop() {
		tvTitle.setText(title);
		tvSearch.setVisibility(View.GONE);
	}
	
	private class MyAdapter extends IndicatorFragmentPagerAdapter {

		public MyAdapter(FragmentManager fragmentManager) {
			super(fragmentManager);
		}

		@Override
		public int getCount() {
			return names.length;
		}

		@Override
		public View getViewForTab(int position, View convertView,
				ViewGroup container) {
			if (convertView == null) {
				convertView = inflate.inflate(R.layout.tab_top, container,false);
			}
			TextView textView = (TextView) convertView;
			textView.setText(names[position % names.length]);
			textView.setPadding(20, 0, 20, 0);
			textView.setTextSize(15);
			
			//根据有异常的项，来对头部进行标志处理
			if (faults[position]) {
				Drawable errorDraw = getResources().getDrawable(
						R.mipmap.icon_error_tip);
				errorDraw.setBounds(0, 0, errorDraw.getMinimumWidth(),
						errorDraw.getMinimumHeight());
				textView.setCompoundDrawables(null, null, errorDraw, null);
			}
			
			
			return convertView;
		}

		@Override
		public Fragment getFragmentForPage(int position) {
			Fragment curFragment = new DetectSystemFragment();
			Bundle bundle = new Bundle();
			bundle.putInt("parentPosition", parentPosition);
			bundle.putInt("childPosition", childPosition);
			bundle.putInt("position", position);
			bundle.putInt("type", type);
			bundle.putString(AppConfig.COMPANY_ID_KEY, company_id);
			bundle.putString("secEquipment", new Gson().toJson(secEquipments.get(position)));
			curFragment.setArguments(bundle);

			return curFragment;
		}

		@Override
		public int getItemPosition(Object object) {
			return FragmentListPageAdapter.POSITION_NONE;
		}

	};
	
	
	void initIndication()
	{
		indicator.setScrollBar(new ColorBar(this, Color.parseColor("#16B0F4"),5));

		// 设置滚动监听
		int selectColorId = R.color.tab_top_on;
		int unSelectColorId = R.color.tab_top;
		int selectSizeId = R.dimen.tab_text_select;
		int unSelectSizeId = R.dimen.tab_text_noselect;
		
		indicator.setOnTransitionListener(new OnTransitionTextListener().setValueFromRes(this, selectColorId, unSelectColorId, selectSizeId, unSelectSizeId));

		indicatorViewPager = new IndicatorViewPager(indicator, mViewPage);
		indicatorViewPager.setAdapter(new MyAdapter(getSupportFragmentManager()));
		indicatorViewPager.setPageOffscreenLimit(1);
		
	}
	
	@OnClick({ R.id.tvBack, R.id.tvSearch })
	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.tvBack:
			finish();
			break;
		case R.id.tvSearch:
			
			break;
		default:
			break;
		}
	}
	
}
